﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!IsPostBack)
		{
			btnViewLog.OnClick = "$get('" + lblLog.ClientID + "').innerHTML = '';";
			txtDate.Text = DateTime.Now.ToString(Tools.GetDateFormat());

			ddlLogNameSufix.Items.Add(new ListItem(Resources.DatabaseStrings.Log_General, Tools.LOG_GENERAL));
			ddlLogNameSufix.Items.Add(new ListItem(Resources.DatabaseStrings.Log_Info, Tools.LOG_INFO));
			ddlLogNameSufix.SelectedIndex = 0;

			btnListLog_Click(null, null);
		}
	}

	protected void btnViewLog_Click(object sender, EventArgs e)
	{
		string strLogFileContent = "";
		string strLogFileContent2 = "";
		try
		{
			string strLogName = Tools.GetLogName(Tools.GetDate(txtDate.Text), ddlLogNameSufix.SelectedValue);
			string strLogFileName = Request.MapPath("~/Logs/" + strLogName);
			strLogFileContent = File.ReadAllText(strLogFileName);
			lblFileSize.Text = strLogFileContent.Length.ToString("N0") + " bytes.";

			Regex regexObj = new Regex(@"^[[](?<Date>.*)[\]] (?<Location>.*):\s?(?<Message>.*)$", RegexOptions.Multiline);
			strLogFileContent2 = regexObj.Replace(strLogFileContent, new MatchEvaluator(ComputeReplacement));
		}
		catch (Exception ex)
		{
			this.Master.SetMessage(ex.Message, true);
			lblFileSize.Text = "-";
		}

		lblLog.Text = "<pre>" + strLogFileContent2.Replace("<PRE>", "&lt;PRE&gt;").Replace("</PRE>", "&lt;/PRE&gt;") + "</pre>";
		upLog.Update();
		btnGetServerTime_Click(null, null);
		System.Web.UI.ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "Log_scrollIntoView", "\n $get('" + lblLog.ClientID + "').scrollIntoView(false); \n ", true);
	}

	protected void btnListLog_Click(object sender, EventArgs e)
	{
		string strLogFileContent = "";
		try
		{
			if (Session["htFileSize"] == null)
				Session["htFileSize"] = new Hashtable();

			string strLogPath = Request.MapPath("~/Logs/");
			string[] arFiles = Directory.GetFiles(strLogPath, "Log*.txt");

			DataTable dt = new DataTable();
			dt.Columns.Add(new DataColumn("FileName", Type.GetType("System.String")));
			dt.Columns.Add(new DataColumn("Info", Type.GetType("System.String")));
			dt.Columns.Add(new DataColumn("FileDate", Type.GetType("System.DateTime")));
			dt.Columns.Add(new DataColumn("FileSize", Type.GetType("System.Int32")));

			foreach (string s in arFiles)
			{
				FileInfo fi = new FileInfo(s);

				DataRow dr = dt.NewRow();
				dr["FileName"] = fi.Name;
				dr["Info"] = fi.Name.Contains("_info") ? 1 : 0;
				dr["FileDate"] = DateTime.Parse(fi.Name.Substring(4, 10));

				if (DateTime.Parse(fi.Name.Substring(4, 10)) > DateTime.Now.AddDays(-7))
					((Hashtable)Session["htFileSize"]).Remove(fi.Name);
				if (!((Hashtable)Session["htFileSize"]).Contains(fi.Name))
					((Hashtable)Session["htFileSize"]).Add(fi.Name, fi.Length);
				dr["FileSize"] = ((Hashtable)Session["htFileSize"])[fi.Name];
				dt.Rows.Add(dr);
			}
			dt.DefaultView.Sort = "FileDate DESC, Info";
			int n = dt.DefaultView.Count;
			if (ddlTop.SelectedValue != "")
				n = Math.Min(n, Convert.ToInt32(ddlTop.SelectedValue));
			for (int i = 0; i < n; ++i )
				strLogFileContent += string.Format("<tr><td><a class='aLink' href='javascript:DoSelectFile(\"" + Convert.ToDateTime(dt.DefaultView[i]["FileDate"]).ToString(CalendarExtender2.Format) + "\", \"" + dt.DefaultView[i]["Info"].ToString() + "\");'>{0}</a>", dt.DefaultView[i]["FileName"].ToString()) + "</td><td align='right'>" + Convert.ToInt32(dt.DefaultView[i]["FileSize"]).ToString("N0") + "</td></tr>\n";
		}
		catch (Exception ex)
		{
			this.Master.SetMessage(ex.Message, true);
		}
		strLogFileContent = "<table>\n<tr><th align='left'>" + Resources.DatabaseStrings.File + "</th><th align='right'>" + Resources.DatabaseStrings.FileSize + "</th></tr>\n" + strLogFileContent + "</table>\n";
		lblLog.Text = "<pre style='margin: 10px'><b>" + Resources.DatabaseStrings.SelectLogFile + ":</b>\n\n" + strLogFileContent.Replace("<PRE>", "&lt;PRE&gt;").Replace("</PRE>", "&lt;/PRE&gt;") + "</pre>";
		upLog.Update();
		lblFileSize.Text = "-";
		upViewLog.Update();
		btnGetServerTime_Click(null, null);
	}

	protected void btnGetServerTime_Click(object sender, EventArgs e)
	{
		lblServerTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
		upGetServerTime.Update();
	}

	public string ComputeReplacement(Match m)
	{
		string s = string.Format("[<span style='color: green'>{0}</span>] <span style='color: red'>{1}</span>: {2}", m.Groups["Date"].Value, m.Groups["Location"].Value, m.Groups["Message"].Value);
		return s;
	}

	protected void btnKillExcel_Click(object sender, EventArgs e)
	{
		KillExcelProcess();
		this.Master.SetMessage("Procesele au fost inchise.", false);
	}

	protected void btnKillWord_Click(object sender, EventArgs e)
	{
		KillWordProcess();
		this.Master.SetMessage("Procesele au fost inchise.", false);
	}

	private void KillExcelProcess()
	{
		try
		{
			Process[] proc = Process.GetProcessesByName("EXCEL");
			for (int jj = 0; jj < proc.Length; jj++)
			{
				proc[jj].Kill();
				proc[jj].WaitForExit();
			}
		}
		catch (Exception ex)
		{
			Tools.ScrieInLog(Server, "ERROR (Admin.aspx.cs) [SessionID='" + Session.SessionID + "', UserName='" + Tools.GetUserName() + "', PathAndQuery='" + this.Request.Url.PathAndQuery + "']:\r\nMessage: " + ex.Message + "\r\nStackTrace: \r\n" + (new System.Diagnostics.StackTrace()).ToString());
		}
	}

	private void KillWordProcess()
	{
		try
		{
			Process[] proc = Process.GetProcessesByName("WINWORD");
			for (int jj = 0; jj < proc.Length; jj++)
			{
				proc[jj].Kill();
				proc[jj].WaitForExit();
			}
		}
		catch (Exception ex)
		{
			Tools.ScrieInLog(Server, "ERROR (Admin.aspx.cs) [SessionID='" + Session.SessionID + "', UserName='" + Tools.GetUserName() + "', PathAndQuery='" + this.Request.Url.PathAndQuery + "']:\r\nMessage: " + ex.Message + "\r\nStackTrace: \r\n" + (new System.Diagnostics.StackTrace()).ToString());
		}
	}

}
